package cn.itsource.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component //认证（登录）授权（权限控制）过滤器
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        //前置过滤器
        return "pre";
    }

    @Override
    public int filterOrder() {
        //通过过滤器级别控制同一类型执行顺序
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //是否需要进行过滤，以后需要在这儿做放行，现在所有的请求都拦截
        return true;
    }

    //登录拦截：这次只做它
    //权限拦截：暂时不考虑
    @Override
    public Object run() throws ZuulException {
       //1 获取请求上下文
        RequestContext context = RequestContext.getCurrentContext();
        //2 从上下文获取请求
        HttpServletRequest request = context.getRequest();
        //3 从请求头获取token
        String token = request.getHeader("token");
        //4 判断是否已经登录：null，redis
        if (StringUtils.isEmpty(token)){
            //4.1 如果没有登录报错
            context.setSendZuulResponse(false);//失败
            context.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
        }
       //4.2 放行
        return null;
    }
}
